/*
 * @Author: yangzonglong
 * @Date: 2020-07-06 14:11:49
 * @version: v1.0.0
 * @Descripttion: 挂载 window app
 * @LastEditors: yangzonglong
 * @LastEditTime: 2023-09-18 14:45:32
 * @Auditor: 
 */
import i18n from './i18n';
import history from './history';
import store from './../redux/store';
import { setLoading } from './../redux/common';
import moment from 'moment';

const getInfoByFunctionCode = (name?: string) => {
  let str = window.location.href;
  const moduleCode = str
    .replace('/core/app', '')
    .replace(location.origin + '/', '')
    .split('/')?.[0];
  const menuList = JSON.parse(sessionStorage.userInfo)?.menuList?.find(
    (item: any) => item.moduleCode === moduleCode
  ) || { menu: [] };

  const childrens = menuList.menu?.reduce((all: any, now: any) => {
    return all.concat(now.children || []);
  }, []);

  let functionUrl = '';
  if (window.location.href.includes('/crud')) {
    functionUrl =
      '/' +
      window.location.pathname
        .replace(`/core/app/${moduleCode}/`, '')
        .replace(`/${moduleCode}/`, '')
        .replace('crud/', '')
        .split('/')[0];
  } else {
    functionUrl =
      '.' +
      window.location.pathname.replace(`/core/app/${moduleCode}/`, '').replace(`/${moduleCode}/`, '').split('/')[0];
  }

  let item: any = {};
  item = childrens.find((item: any) => item?.functionUrl.replace(`${moduleCode}`, '') === functionUrl);
  if (!item) {
    item = childrens.find((item: any) => item?.functionUrl?.indexOf(functionUrl) > -1);
  }

  const time = moment().format('YYMMDD');
  const fileName = localStorage.i18nextLng === 'en' ? item.functionEnName || item.functionName : item.functionName;
  return fileName + (name || '') + time;
};

function t(k: string) {
  const projectText = i18n.t(`project:${k}`);
  if (projectText !== k) return projectText;

  const commonText = i18n.t(k);
  if (commonText !== k) return commonText;

  return i18n.t(`models:${k}`);
}

let axiosCount = 0;

function handLoading(type: string) {
  if (type === 'show') {
    axiosCount = axiosCount + 1;
  } else {
    axiosCount = axiosCount === 0 ? 0 : axiosCount - 1;
  }

  // 加入top loading的逻辑
  const topWindow = window.top as Window & { onHandleLoading: (type: string) => any; };
  if (topWindow.onHandleLoading) {
    topWindow.onHandleLoading(type);
  } else {
    store.dispatch(setLoading(axiosCount > 0));
  }
}

export default {
  history,
  t: t,
  MOMENT_FORMAT_TIME: 'YYYY/MM/DD HH:mm',
  MOMENT_FORMAT_DATE: 'YYYY/MM/DD',
  DEV: process.env.NODE_ENV === 'development',
  showLoading: () => handLoading('show'),
  hideLoading: () => handLoading('hide'),
  showIsLoginFailure: () => { },
  getInfoByFunctionCode
};